<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\api\permissions;

use App\Common\Repositories\System\CustomerAdminRepository;
use App\Exception\AppException;
use App\Model\Excel;
use Hyperf\Coroutine\Coroutine;
use Hyperf\DbConnection\Db;
use xsl\basic\BaseController;
use xsl\services\ExcelService;

class Users extends BaseController
{
    protected $repository;

    public function __construct(CustomerAdminRepository $repository)
    {
        $this->repository = $repository;
    }

    public function index()
    {
        $params = $this->request->all();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $params['no_admin'] = [1];
        $result = $this->repository->getWhereList(["*"], $params, true, intval($page), intval($limit));
        return $this->pageSuccess($limit, $result->total(), $result->items());
    }

    public function enable($id){
        try {
            return $this->success($this->repository->toggleBy($id));
        } catch (AppException $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function read($id){
        $info = $this->repository->getWhere(['id'=>$id],["id","username","account","email"]);
        $info->jobs = [];
        $info->roles = Db::table('customer_admin_has_roles')->where("admin_id", $id)->pluck('role_id');
        return $this->success($info);
    }

    public function delete($id){
        $this->repository->delete($id);
        Db::table('customer_admin_has_roles')->where("admin_id", $id)->delete();
        return $this->success();
    }

    public function create(){
        $params = $this->request->all();

        $data = [];
        $data['username'] = $params['username'];
        $data['account'] = $params['account'];
        $data['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
        $data['email'] = $params['email'];
        $data['creator_id'] = $this->request->adminId();
        $data['status'] = 1;
        $data['created_at'] = time();
        $admin_id = $this->repository->insertGetId($data);
        if($admin_id){
            $roles = [];
            foreach ($params['roles'] as $role){
                $roles[] = [
                    'admin_id' => $admin_id,
                    'role_id' => $role
                ];
            }
            Db::table('customer_admin_has_roles')->insert($roles);
        }
        return $this->success();
    }

    public function update($id){
        $params = $this->request->all();

        $info = $this->repository->get($id);
        $data = [];
        $data['username'] = $params['username'];
        $data['account'] = $params['account'];
        if(!empty($params['password'])){
            $data['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
        }
        $data['email'] = $params['email'];
        $data['updated_at'] = time();
        $this->repository->update($id,$data);
        Db::table('customer_admin_has_roles')->where("admin_id", $id)->delete();
        if(!empty($params['roles'])){
            $roles = [];
            foreach ($params['roles'] as $role){
                $roles[] = [
                    'admin_id' => $info->id,
                    'role_id' => $role
                ];
            }
            Db::table('customer_admin_has_roles')->insert($roles);
        }
        return $this->success();
    }



    /**
     * 导出
     */
    public function export()
    {
        $params = $this->request->all();
        $excel = new Excel();
        $type = "users";
        $excel_id = $excel->insertGetId([
            'admin_id'  => $this->request->adminId(),
            'type'      => $type,
            'created_at'=> time()
        ]);
        $params['no_admin'] = [1];
        $data = ['where' => $params, 'type' => $type, 'excel_id' => $excel_id];
        \Hyperf\Support\make(ExcelService::class)->user_excel($data);
        return $this->success([],'开始导出数据');
    }
}
